package com.huang.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserDetailsSe implements UserDetailsService {

    //注入创建密码的类
    @Autowired
   private BCryptPasswordEncoder passwordEncoder;
    //1.基于用户名从数据库查询用户信息
    //User user=userMapper.selectUserByUsername(username);
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!"jake".equals(username)) {
            throw  new UsernameNotFoundException("用户不存在");

        }
        //2.将用户信息封装到UserDetails对象中并返回
        //假设这个密码是从数据库查询出来的
        String pwd=passwordEncoder.encode("1111");
        //假设这个权限信息也是从数据库查询到的
        //假如分配权限的方式是角色,编写字符串时用"ROLE_"做前缀
        List<GrantedAuthority> authorities=
                AuthorityUtils.commaSeparatedStringToAuthorityList(
                        "ROLE_admin,ROLE_normal,sys:res:retrieve,sys:res:create");
        User user =new User(username, pwd, authorities);

        return user;
    }
}
